<!-- 业态配置 -->
<template>
  <div class="management-tree justify-between">
    <div class="btn-right flex">
      <el-button type="primary" size="mini" @click="addNode">添加类型</el-button>
      <el-button type="primary" size="mini" @click="downTemplate" class="margin-right-10">下载模板</el-button>
      <el-upload :show-file-list="false" action accept="" :http-request="event => importData(event.file)">
        <el-button type="primary" size="mini">导入</el-button>
      </el-upload>
    </div>

    <div class="flex">
      <div class="tree-box flex padding-top-bottom-10 padding-left-right-25">
        <el-tree ref="menuTree" :data="treeData" :props="defaultProps" node-key="primaryKey" :default-expanded-keys="defaultExpandIds" @node-expand="handleNodeExpand" @node-collapse="handleNodeCollapse">
          <div class="flex justify-between tree-item align-center" slot-scope="{ node, data }">
            <div class="font-size-16 onn-ellipsis tree-title" v-tooltip.content="data.subjectName">{{ data.subjectName }}</div>
            <div>
              <el-button type="text" @click.stop="addNode(node, data)" v-if="!data.chargeItemKey">添加</el-button>
              <el-button type="text" @click.stop="editNode(node, data)" class="margin-left-15">编辑</el-button>
              <el-button type="text" @click.stop="deleteNode(node, data)" class="color-red margin-left-15">删除</el-button>
            </div>
          </div>
        </el-tree>
      </div>
      <div v-if="isEditForm" class="form-box flex justify-center">
        <div class="form-box-item">
          <form-common :filed-list="budgetFiledList" ref="form" :formObj="formObj" @selectChange="selectChange"></form-common>
          <div slot="footer" class="dialog-footer">
            <el-button class="f-right margin-left-10" size="mini" type="primary" @click="saveNode">保存</el-button>
            <el-button class="f-right" size="mini" @click="cancleNode">取 消</el-button>
          </div>
        </div>
      </div>
    </div>

    <el-dialog :visible.sync="chargeDialog" width="60%" title="关联事项" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-tree ref="chargeTree" :data="chargeItemList" :props="defaultChargeProps" show-checkbox node-key="primaryKey">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ data.sortCodePath }}{{ data.chargeItemName }}</span>
        </span>
      </el-tree>
      <span slot="footer">
        <el-button size="mini" @click="chargeDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="saveCharge">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import formCommon from '@g/components/form/formCommon.vue';
  import { budgetFiledList } from '../../../assets/form.js';
  import { apiBudgetAdd, apiBudgetUpdate, apiBudgetDelete, apiBudgetTree, apiBudgeImport, bussinessTree } from '../../../api/index';
  import { requestTips, askDialog } from '@/common/js/utils.js';
  import { apiConstant } from '@a/index';

  export default {
    data() {
      return {
        defaultProps: {
          children: 'child',
          label: 'subjectName',
        },
        isEditForm: false,
        treeData: [],
        budgetFiledList: budgetFiledList,
        parentData: {},
        defaultExpandIds: [],
        rootKey: '', //根节点
        formObj: {},

        defaultChargeProps: {
          children: 'child',
          label: 'chargeItemName',
        },
        choosedChargeList: [],
        chargeItemList: [],
        chargeDialog: false,
      };
    },

    methods: {
      // 数据源tree
      async getTree() {
        let res = await apiBudgetTree({ status: 1, enterpriseid: this.$route.query.key, chargeItemShow: true });
        if (res.rows && res.rows.length > 0) {
          this.treeData = res.rows[0].child || [];
          this.rootKey = res.rows[0].primaryKey;
        }
      },

      // 科目类型
      async getConstant() {
        let res = await apiConstant();
        this.budgetFiledList.forEach((item, index) => {
          if (item.bindFieldName == 'subjectType') {
            item.optionList = res.subjectType;
          }
        });
      },

      // 导入
      importData(file) {
        apiBudgeImport(file).then(res => {
          this.$message.success('上传成功');
          this.GetData();
        });
      },

      // 添加节点
      addNode(node, data) {
        this.isEditForm = true;
        this.parentData = data || {};
        this.choosedChargeList = [];
        this.$nextTick(() => {
          this.$refs.form.initModel();
          this.budgetFiledList[0].bindFieldVal = '变化';
          this.budgetFiledList.forEach((item, index) => {
            if (item.bindFieldName == 'calculateMethod') {
              item.bindFieldVal = 1;
            } else {
              item.bindFieldVal = '';
            }
          });
        });
      },

      // 保存节点
      async saveNode() {
        let model = this.$refs.form.validateForm();
        if (!model) return;
        model.parentId = model.parentId || this.parentData.primaryKey || this.rootKey || '';
        model.chargeItemList = this.choosedChargeList.map(item => item.primaryKey);
        let res = model.primaryKey ? await apiBudgetUpdate(model) : await apiBudgetAdd(model);
        requestTips(res, () => {
          this.getTree();
          this.cancleNode();
        });
      },

      // 取消节点
      cancleNode() {
        this.$refs.form.clearValidateForm();
        setTimeout(() => {
          this.isEditForm = false;
        });
      },

      // 编辑节点
      editNode(node, data) {
        this.isEditForm = true;
        //后端返回的字段不是我们想要的，转一下
        data.chargeItemList?.forEach(item => {
          item.primaryKey = item.bizId;
          item.chargeItemName = item.bizName;
        });
        this.choosedChargeList = data.chargeItemList || [];
        data.chargeItemName = data.chargeItemList?.map(item => item.bizName).join('，') || '';
        this.formObj = data;
      },

      // 删除节点
      deleteNode(node, data) {
        askDialog('确认删除？', async () => {
          const res = await apiBudgetDelete({ primaryKey: data.primaryKey });
          requestTips(res, () => {
            this.getTree();
            this.handleNodeCollapse(data);
          });
        });
      },

      // 字段回显
      setFiledVal(list, row) {
        list.forEach(item => {
          for (let i in row) {
            if (i == item.bindFieldName) {
              item.bindFieldVal = row[i];
            }
          }
        });
      },

      //下载模板
      downTemplate() {
        let a = document.createElement('a');
        a.style.display = 'none';
        a.href = '/static/budgetTemplate.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      },

      //打开关联事项弹框
      async selectChange(data) {
        if (data.filedName == 'chargeItemName') {
          let chargeItemIdList = this.choosedChargeList.map(item => item.primaryKey);
          this.chargeDialog = true;
          this.$nextTick(() => {
            this.$refs.chargeTree.setCheckedKeys(chargeItemIdList);
          });
        }
      },

      //保存关联事项
      saveCharge() {
        let choosedChargeList = this.$refs.chargeTree.getCheckedNodes(false, false);
        this.choosedChargeList = choosedChargeList;
        let chargeItemName = choosedChargeList.map(item => item.chargeItemName).join(',');
        this.$refs.form.setFiledSource('chargeItemName', chargeItemName);
        this.chargeDialog = false;
      },

      //关联事项数据源
      async getChargeList() {
        let res = await bussinessTree({
          mapBizId: this.$route.query.key,
        });
        if (res.rows && res.rows.length > 0) {
          this.chargeItemList = res.rows[0].child;
        }
      },

      //折叠打开
      handleNodeExpand(data) {
        let arr = [];
        this.defaultExpandIds.forEach((item, index) => {
          arr.push(item.primaryKey);
        });
        if (arr.indexOf(data.primaryKey) < 0) {
          this.defaultExpandIds.push(data.primaryKey);
        }
      },

      //折叠关闭
      handleNodeCollapse(data) {
        this.defaultExpandIds.splice(this.defaultExpandIds.indexOf(data.primaryKey), 1);
      },
    },

    created() {
      this.getConstant();
      this.getChargeList();
    },

    components: { formCommon },
  };
</script>

<style lang="scss" scoped>
  .btn-right {
    position: absolute;
    top: -50px;
    right: 20px;
  }
  .tree-box {
    width: 40%;
  }
  .form-box {
    width: 60%;
    .form-box-item {
      width: 70%;
    }
  }
  .el-tree,
  .tree-item {
    width: 100%;
  }
  .tree-title {
    width: 260px;
  }
  //超出一行省略
  .onn-ellipsis {
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 1;
    line-clamp: 1;
    -webkit-box-orient: vertical;
  }
</style>
